package com.qf.events.listeners;

import com.qf.events.DeviceOnOffLineEvent;
import com.qf.pojo.Device;
import com.qf.service.DeviceService;
import com.qf.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/*
杨威
2022/1/7
13:16
*/
@Component
public class DeviceStatusChangeListener {
    @Autowired
    DeviceService deviceService;
    @EventListener
    @Async
    public void onEvent(DeviceOnOffLineEvent deviceOnOffLineEvent){
        String id = deviceOnOffLineEvent.getId();
        Date time = deviceOnOffLineEvent.getEventTime();
        Long status = deviceOnOffLineEvent.getStatus();
        String ip = deviceOnOffLineEvent.getIp();

        //修改设备的在线状态
        Device device=new Device();
        device.setDeviceId(id);
        //上线时间
        device.setConnectTime(time);
        //设置断开时间, 两个都设置的原因是因为我们只需要一个数据,是根据状态选择的,所以即便设置两个也只会用一个
        device.setLostConnectTime(deviceOnOffLineEvent.getEventTime());
        device.setIsOnline(status);
        device.setCurrentConnectIp(ip);

        //如果登录的时候有ip我们才设置登录的地址
        if(StringUtils.hasText(deviceOnOffLineEvent.getIp())){
            device.setConnectLocation(RequestUtil.getLocationByIp(deviceOnOffLineEvent.getIp()));
        }
        deviceService.updateDeviceOnlineStaus(device);
    }
}
